/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package abricots.net;

import abricots.MyLog;
import abricots.net.common.MessageDispatcher;
import abricots.entity.Entity;
import abricots.game.GameEnv;
import abricots.net.common.GameMessage;
import abricots.net.common.GameMessage.CommandsMessage;
import abricots.net.common.GameMessage.GameTimeSyncMessage;
import abricots.net.common.GameMessage.WorldDiffMessage;
import abricots.net.common.GameMessage.EntityMessage;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.minlog.Log;

/**
 *
 * @author charly
 */
public class ServerMessageDispatcher extends MessageDispatcher {

    private final MyLog log = new MyLog(getClass().getSimpleName(), Log.LEVEL_DEBUG);
    private GameServer server;
    private GameEnv env;

    public ServerMessageDispatcher(GameServer server, GameEnv env) {
        this.server = server;
        this.env = env;
    }

    @Override
    public void dispatchMessage(Object message, Connection connection) {
        super.dispatchMessage(message, connection);
    }

    @Override
    public void dispatchGameSyncMessage(GameTimeSyncMessage message, Connection connection) {
        ServerConnection serverConnection = (ServerConnection) connection;
        GameMessage.GameTimeSyncMessage timeMessage = new GameMessage.GameTimeSyncMessage();
        timeMessage.gameTime = message.gameTime;
        timeMessage.newGameTime = env.getTimeManager().getGameTime();
        serverConnection.send(timeMessage);
    }

    @Override
    public void dispatchEntitymessage(EntityMessage message, Connection connection) {
        ServerConnection serverConnection = (ServerConnection) connection;
        if (message.entityId == -1 && message.localEntityId >= 0) { //new entity
            serverConnection.addNewEntity(message);
        } else {
            log.warn("Unknown message received : " + message);
        }
    }

    @Override
    public void dispatchWorldDiffMessage(WorldDiffMessage message, Connection connection) {
    }

    @Override
    public void dispatchCommandsMessage(CommandsMessage message, Connection connection) {
        ServerConnection sc = (ServerConnection) connection;
        sc.getAckedFramesManager().newAckedState(((GameMessage) message).ackId);
        sc.addCommands(message);
    }
}
